//
//  AppDelegate.m
//  Edu_iOS2018
//
//  Created by yanyan on 2017/12/28.
//  Copyright © 2017年 yanyan. All rights reserved.
//

#import "AppDelegate.h"
#import "UIStory_Main.h"
#import "WXApi.h"
#import "ECManager_Pay.h"
#import <AlipaySDK/AlipaySDK.h>
#import "CYUIAlertView.h"


#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import "ECManager_Pay.h"
//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//新浪微博SDK头文件
#import "WeiboSDK.h"

#import <AVFoundation/AVFoundation.h>

#import "DHGuidePageHUD.h"


@interface AppDelegate (){
    UIBackgroundTaskIdentifier _bgTaskId;
}
@property(nonatomic,strong)UIStory_Main *uistory_tab;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.uistory_tab = [[UIStory_Main alloc]init];
    self.window.backgroundColor = [UIColor whiteColor];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self settingsForBars];
    self.window.rootViewController = self.uistory_tab.tabBarController;
    [self.window makeKeyAndVisible];
//    [self registerNotifications];
    [WXApi registerApp:WX_APPID];
    [self shareSDKConfig];
    
    [self listenNetWorkingStatus];
    
    [self welcomePageConfig];
    
    return YES;
}
-(void)settingsForBars{
    // 导航的颜色
    [UINavigationBar appearance].tintColor = [UIColor colorWithHex:0x333333];// [UIColor colorWithRed:0.2706 green:0.2706 blue:0.2706 alpha:1];
    // 导航 title 的颜色和字体
    [UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRGBRed:51 green:51 blue:51],NSFontAttributeName:[UIFont boldSystemFontOfSize:16*kPercentage]};
    // 导航的背景色the bar's background,
    [UINavigationBar appearance].barTintColor = [UIColor whiteColor];
//    [UINavigationBar appearance].barTintColor = [UIColor darkGrayColor];

    //自定义返回按钮  (全局设置)
//    UIImage *backButtonImage = [UIImage imageNamed:@"Mine_back"];//[[UIImage imageNamed:@"Mine_back"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
//    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    UIImage *backButtonImage = [[UIImage imageNamed:@"Mine_back"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];// [UIImage imageNamed:@"Mine_back"];//
//   [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage  forState:UIControlStateNormal barMetrics:UIBarMetricsCompact];
    //将返回按钮的文字position设置不在屏幕上显示
//        [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -100) forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setBackIndicatorImage:[UIImage imageNamed:@"Mine_back"]];
    [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"Mine_back"]];
//    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    // 设置导航 字体
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:0x333333],NSFontAttributeName:[UIFont boldSystemFontOfSize:15]} forState:UIControlStateNormal];
// 设置 tabbar 的颜色
    [UITabBar appearance].barTintColor = [UIColor whiteColor];
    //选中的tabbar的颜色
    //    [UITabBar appearance].selectedImageTintColor = [UIColor colorWithRed:0.2706 green:0.2706 blue:0.2706 alpha:0.2706];
    // 选中tabbar的颜色
    [UITabBar appearance].tintColor = ECTHEMESELECTEDCOLOR;
}
//添加通知。
- (void)registerNotifications{
    
    UIMutableUserNotificationAction *accept = [[UIMutableUserNotificationAction alloc]init];
    accept.identifier = @"LookId";
    accept.title = @"查看";
    accept.activationMode = UIUserNotificationActivationModeBackground;
    accept.destructive = NO;
    accept.authenticationRequired = NO;
    
    UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc]init];
    category.identifier = @"newCourse";
    [category setActions:@[accept] forContext:UIUserNotificationActionContextDefault];
    if (![[UIApplication sharedApplication]isRegisteredForRemoteNotifications]) {
        [[UIApplication sharedApplication]registerForRemoteNotifications];
    }
    NSSet *categorys = [NSSet setWithObjects:category, nil];
    UIUserNotificationType  types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:types categories:categorys];
    [[UIApplication sharedApplication]registerUserNotificationSettings:notiSettings];
    [[UIApplication sharedApplication]registerForRemoteNotifications];
}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //支付宝支付
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        WeakSelf(weakSelf);
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            DLog(@"在主线程----%d",[[NSThread currentThread] isMainThread]);
//            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf postNotifacationForAliPayResult:resultDic];
//            });
        }];
    } else {// 微信支付
    if ([url.host isEqualToString:@"pay"]) {
        [WXApi handleOpenURL:url delegate:[ECManager_Pay sharedInstance]];
    }
    }
    return YES;
}

-(void)shareSDKConfig{
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeSinaWeibo),
                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformTypeQQ),
                                        ]
                             onImport:^(SSDKPlatformType platformType){
         switch (platformType){
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
    onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo){
         
         switch (platformType){
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"2457264070"
                                           appSecret:@"bf5f698703d3ebac543ce817e9921cb5"
                                         redirectUri:@"http://www.sdkhcm.com"
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx7151cc4f9794c50d"
                                       appSecret:@"7f41e53c508a30922714b4767abd0839"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1106749202"
                                      appKey:@"Omdz5XVGMMkSpmAB"
                                    authType:SSDKAuthTypeBoth];
                 break;
                 
             default:
                 break;
         }
     }];
}


-(void)listenNetWorkingStatus{
    //1:创建网络监听者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //2:获取网络状态
    /*
     AFNetworkReachabilityStatusUnknown          = 未知网络，
     AFNetworkReachabilityStatusNotReachable     = 没有联网
     AFNetworkReachabilityStatusReachableViaWWAN = 蜂窝数据
     AFNetworkReachabilityStatusReachableViaWiFi = 无线网
     */
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有联网");
                [MBProgressHUD showTipMessageInWindow:@"网络失去连接"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据");
                //[MBProgressHUD showTipMessageInWindow:@"数据网络已连接"];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"无线网");
                //[MBProgressHUD showTipMessageInWindow:@"WiFi网络已连接"];
                break;
            default:
                break;
        }
    }];
    
    //开启网络监听
    [manager startMonitoring];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        WeakSelf(weakSelf);

        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            DLog(@"支付宝--------%@",resultDic);
//  发送通知在主线程
//            dispatch_async(dispatch_get_main_queue(), ^{
            
                [weakSelf postNotifacationForAliPayResult:resultDic];
//            });
            
            
        }];
    } else {
        // 微信支付
        if ([url.host isEqualToString:@"pay"]) {
            [WXApi handleOpenURL:url delegate:[ECManager_Pay sharedInstance]];
        }
    }
    return YES;
}
-(void)postNotifacationForAliPayResult:(NSDictionary *)resultDic{
    if ([[resultDic valueForKey:@"resultStatus"]integerValue] == 9000) {
        [[NSNotificationCenter defaultCenter]postNotificationName:kNotifactionAlipayPaySuccess object:resultDic];
    } else {
        [[NSNotificationCenter defaultCenter]postNotificationName:kNotifactionAlipayPayFail object:resultDic];
    }
}

-(void)welcomePageConfig{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"first_setup"] == 0) {
        DHGuidePageHUD *pageView = [[DHGuidePageHUD alloc]dh_initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) imageNameArray:@[@"guideImage1.png",@"guideImage2.png",@"guideImage3.png"] buttonIsHidden:NO];
        [self.window addSubview:pageView];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:1 forKey:@"first_setup"];
        [defaults synchronize];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    //允许后台播放音乐
    //[application beginBackgroundTaskWithExpirationHandler:nil];
    
    //开启后台处理多媒体事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    //后台播放
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    //这样做，可以在按home键进入后台后 ，播放一段时间，几分钟吧。但是不能持续播放网络歌曲，若需要持续播放网络歌曲，还需要申请后台任务id，具体做法是：
    _bgTaskId=[AppDelegate backgroundPlayerID:_bgTaskId];
}

//实现一下backgroundPlayerID:这个方法:
+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId{
    //设置并激活音频会话类别
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    //允许应用程序接收远程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    //设置后台任务ID
    UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
    newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];
    }
    return newTaskId;
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
